import Redis from 'ioredis';

type RedisError = Error | undefined | null
export type RedisSetResult = "OK" | undefined
export type RedisGetResult = string | undefined | null

class RedisServer {
    static redisClient: Redis | null = null
    // 连接redis
    static redisConnect() {
        const config = {
            host: process.env.NODE_BASE_URL,
            password: process.env.NODE_REDIS_PASSWORD,
            port: Number(process.env.NODE_REDIS_PORT),
            db: Number(process.env.NODE_REDIS_DB)
        }
        if (!process.env.NODE_REDIS_PASSWORD) {
            delete config.password
        }
        this.redisClient = new Redis(config);
    }
    static cb<T>(resolve: (value: (PromiseLike<T> | T)) => void, reject: (reason?: RedisError) => void, error: RedisError, result: T) {
        error ? reject(error) : resolve(result);
        if (this.redisClient) {
            (this.redisClient as Redis).quit()
            this.redisClient = null
        }
    }
    // 数据存入redis
    static redisSet(key: string, value: string, ttl: null | number = null): Promise<RedisSetResult> {
        return new Promise((resolve, reject) => {
            if (!this.redisClient) this.redisConnect()
            return ttl ? (this.redisClient as Redis).set(key, value, 'EX', ttl, (error: RedisError, result: RedisSetResult) => {
                this.cb<RedisSetResult>(resolve, reject, error, result)
            }) : (this.redisClient as Redis).set(key, value, (error: RedisError, result: RedisSetResult) => {
                this.cb<RedisSetResult>(resolve, reject, error, result)
            })
        })
    }
    // 获取redis中的数据
    static redisGet(key: string): Promise<RedisGetResult> {
        return new Promise((resolve, reject) => {
            if (!this.redisClient) this.redisConnect();
            (this.redisClient as Redis).get(key, (error: RedisError, result: RedisGetResult) => {
                this.cb<RedisGetResult>(resolve, reject, error, result)
            });
        })
    }
}

export default RedisServer

